package com.farewell.blog.service.impl;

import com.farewell.blog.mapper.CommentMapper;
import com.farewell.blog.pojo.Comment;
import com.farewell.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Farewell
 * @date 2021/2/10
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    private List<Comment> allComments = new ArrayList<>();

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        // 包含一级评论和二级评论
        List<Comment> comments = commentMapper.listCommentByBlogId(blogId);
        // 对二级评论再进行迭代查找所有的子集直到没有回复的评论子集
        for (Comment comment : comments) {
            // 获取二级评论
            List<Comment> replyComments = comment.getReplyComments();
            if (!replyComments.isEmpty()) {
                // 递归查找
                searchAllComments(replyComments);
            }
            comment.setReplyComments(allComments);
            allComments = new ArrayList<>();
        }
        return comments;
    }

    private void searchAllComments(List<Comment> replyComments) {
        if (!replyComments.isEmpty()) {
            for (Comment replyComment : replyComments) {
                allComments.add(replyComment);
                List<Comment> replyCommentsSon = commentMapper.listCommentByBlogIdAndParentNotNull(replyComment.getId());
                searchAllComments(replyCommentsSon);
            }
        }
    }

    @Override
    public void saveComment(Comment comment) {
        comment.setCreateTime(new Date());
/*        if ("572783092@qq.com".equals(comment.getEmail()) && "Farewell".equals(comment.getNickname())) {
            comment.setAdminComment(true);
            comment.setAvatar("/images/me.jpg");
        }else {
            comment.setAvatar("/images/avatar.png");
        }*/
        commentMapper.insert(comment);
    }
}
